//
//  CompositeAppDelegate.swift
//  SwiftProject
//
//  Created by qindong on 2021/3/15.
//

import UserNotifications

typealias AppDelegateType = UIResponder & UIApplicationDelegate & UNUserNotificationCenterDelegate

// 组合模式管理器 负责调用子模块中的函数
class CompositeAppDelegate : AppDelegateType  {
    private let appDelegates: [AppDelegateType]

    init(appDelegates: [AppDelegateType]) {
        self.appDelegates = appDelegates
    }

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        appDelegates.forEach { _ = $0.application?(application, didFinishLaunchingWithOptions: launchOptions) }
        return true
    }

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        appDelegates.forEach { _ = $0.application?(application, didRegisterForRemoteNotificationsWithDeviceToken: deviceToken) }
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        appDelegates.forEach { _ = $0.applicationDidEnterBackground?(application)
        }
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        appDelegates.forEach { _ = $0.applicationDidBecomeActive?(application)
        }
    }
    
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        appDelegates.forEach { _ = $0.application?(application, didReceiveRemoteNotification: userInfo, fetchCompletionHandler: completionHandler)
        }
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        appDelegates.forEach { _ = $0.applicationWillEnterForeground?(application)
        }
    }
    
    func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
        appDelegates.forEach { _ = $0.application?(app, open: url, options: options) }
        return true
    }

//    func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
//        appDelegates.forEach{ _ = $0.application?(application, open: url, sourceApplication: sourceApplication, annotation: annotation) }
//        return true
//    }

    func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
        appDelegates.forEach{ _ = $0.application?(application, continue: userActivity, restorationHandler: restorationHandler) }
        return true
    }

    func applicationWillTerminate(_ application: UIApplication) {
        appDelegates.forEach{ $0.applicationWillTerminate?(application) }
    }
}
